//
//  FlashCardViewController.m
//  FingerChinese
//
//  Created by luar on 14/02/2010.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "FlashCardViewController.h"
#import "UIPageScrollView.h"
#import "PageView.h"
#import "CardView.h"
#import "FlashCard.h"
#import "CardViewBackground.h"
#import "NavigationTitle.h"
#import <AVFoundation/AVFoundation.h>

@implementation FlashCardViewController

@synthesize cardA, borderW, borderH, cardW, cardH, lbSize, cardX, cardY, header_en, header_cn;


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
	self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
	fingerPageNo = -1;
	lbSize = 25;
	isFingerPage = NO;
	cardA = [[NSMutableArray array] retain];
	UIImage *border = [UIImage imageNamed:@"flashcardBorder.png"];
	defaultBorderW = borderW = border.size.width;
	defaultBorderH = borderH = border.size.height;
	[border release];
	return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	
	bg = [[CardViewBackground alloc] initWithImage: 
					   [UIImage imageNamed:@"flashcardBG.png"]];
	bg.userInteractionEnabled = YES;
	bg.backgroundColor = [UIColor blackColor];
	bg.contentMode = UIViewContentModeCenter;
	[self.view insertSubview:bg	atIndex:0];

	cardW = (cardW > 0) ? cardW : defaultBorderW;
	cardH = (cardH > 0) ? cardH : defaultBorderH;
	
	_scrollView.pageQuantity = [cardA count];
	_scrollView.frameWidth = defaultBorderW;
	_scrollView.frameHeight = defaultBorderH;
	_scrollView.canDoubleTapZoom = NO;
	_scrollView.directionalLockEnabled = YES;
	if (isHorizontalScroll) {
		_scrollView.alwaysBounceVertical = NO;
	} else {
		_scrollView.alwaysBounceHorizontal = NO;
	}

	[_scrollView initPage];
	[self updateCardWidth];
	
	if (initPageNo > -1) {
		[self jumpPage:initPageNo];	
	} else {
		[self jumpPageDid:1 pageQuantity:_scrollView.pageQuantity];	
	}	
	
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cardTouchesBegan:) name:@"CardTouchesBegan" object:nil];
}

- (void)updateInterfaceOrientation {
	[super updateInterfaceOrientation];
	[self updateCardWidth];
	[_scrollView jumpPage:curPageNo];
}

- (void)updateCardWidth {
	int w2 = (cardX > 0) ? cardX : ([UIScreen mainScreen].bounds.size.width-cardW)/2;
	int h2 = (cardY > 0) ? cardY : ([UIScreen mainScreen].bounds.size.height-cardH)/2;
	bg.transform = CGAffineTransformMakeRotation(0);
	bg.frame = [UIScreen mainScreen].bounds;
	_scrollView.frame = CGRectMake(w2, h2, cardW, cardH);
	if (isHorizontalScroll) {
		_scrollView.contentSize = CGSizeMake(cardW+1, cardH);
	} else {
		_scrollView.contentSize = CGSizeMake(cardW, cardH+1);
	}
	borderW = defaultBorderW/_scrollView.minimumZoomScale;
	borderH = defaultBorderH/_scrollView.minimumZoomScale;
	cardOrientation = 1;	
	if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft || [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight) {
		bg.center = CGPointMake([UIScreen mainScreen].bounds.size.height/2, [UIScreen mainScreen].bounds.size.width/2);
		int offset = ([UIScreen mainScreen].bounds.size.height-[UIScreen mainScreen].bounds.size.width)/2;
		_scrollView.frame = CGRectMake(w2+offset, h2-offset, cardW, cardH);
	}
	NSLog(@"updateCardWidth %i %i, %i %i, %i %i, %f", w2, h2, defaultBorderW, defaultBorderH, borderW, borderH, _scrollView.minimumZoomScale);
}

# pragma mark -
# pragma mark UIPageScrollView

- (PageView*)genPage:(NSInteger)pageIndex isNewPage:(BOOL)newPage {
	FlashCard *fc = [cardA objectAtIndex: pageIndex];
	
	PageView *_page = [_scrollView genPage:pageIndex isNewPage:newPage];
	CGRect frame1 = CGRectMake(0, 0, borderW, borderH);		// black view
	CGRect frame2 = CGRectMake(0, 0, borderW, borderH);		// card
	CGRect frame3 = CGRectMake(0, 10, borderW, 15);		// header: english/chinese
	
	UIView *view = [[[UIView alloc] initWithFrame:frame1] autorelease];
	UIImageView *img1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"flashcardBorder.png"]];
	CardView *view1 = [[[CardView alloc] initWithFrame:frame2] autorelease];
	UILabel *header1 = [[[UILabel alloc] initWithFrame:frame3] autorelease];
	header1.text = header_en;
	int lbHeight_en;
	if (cardOrientation == 1) {
		lbHeight_en = fc.lbHeight_en1;
	} else {
		lbHeight_en = fc.lbHeight_en3;
		img1.transform = CGAffineTransformMakeRotation(-1.57079632679);
		img1.center = CGPointMake(borderW/2, borderH/2);
	}
	UILabel *lb1 = [[[UILabel alloc] initWithFrame:CGRectMake(0, (borderW-lbHeight_en)/2, borderW, lbHeight_en)] autorelease];
	lb1.text = fc.lb_en;
	[view1 addSubview:img1];
	[view1 addSubview:header1];
	[view1 addSubview:lb1];
	[img1 release];
	
	CardView *view2 = [[[CardView alloc] initWithFrame:frame2] autorelease];
	UIImageView *img2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@.png", fc.file]]];
	UILabel *header2 = [[[UILabel alloc] initWithFrame:frame3] autorelease];
	header2.text = header_cn;
	if (cardOrientation == 3) {
		img2.transform = CGAffineTransformMakeRotation(-1.57079632679);
		img2.center = CGPointMake(borderW/2, borderH/2);
	}
	[view2 addSubview:img2];
	[view2 addSubview:header2];
	[img2 release];
	
	header1.backgroundColor = header2.backgroundColor = lb1.backgroundColor = [UIColor clearColor];
	header1.textAlignment = header2.textAlignment = lb1.textAlignment = UITextAlignmentCenter;
	header1.font = header2.font = [UIFont boldSystemFontOfSize:12];
	lb1.lineBreakMode = UILineBreakModeWordWrap;
	lb1.numberOfLines = 0;
	lb1.font = [UIFont systemFontOfSize:lbSize];
	
	view1.isFace = YES;
	view1.backCard = view2;
	view2.isFace = NO;
	view2.backCard = view1;
	view1.cardIndex = view2.cardIndex = pageIndex;
	
	if (fc.isFaced) {
		[view addSubview:view1];
	} else {
		[view addSubview:view2];
	}
	
	[_page addSubview:view];
	return _page;
}

- (void)jumpPageDid:(int)_pageNo pageQuantity:(int)pageQuantity {
	[super jumpPageDid:_pageNo pageQuantity:pageQuantity];
	curCardFlip = -1;
	curPageNo = _pageNo-1;
}

#pragma mark -

- (void)cardTouchesBegan:(NSNotification *)notification {
	if (curCardFlip < 0) {
		CardView *card = [notification object];
		UIView *view = [card superview];
		FlashCard *fc = [cardA objectAtIndex: card.cardIndex];
		curCardFlip = card.cardIndex;
		
		NSLog(@"FlashCard cardTouchesBegan %@ , isFace: %i , backCard: %@ , view: %@", card, card.isFace, card.backCard, view);
		[UIView beginAnimations:nil context:nil];
		[UIView setAnimationDuration:0.5];
		[UIView setAnimationDelegate:self];
		[UIView setAnimationDidStopSelector:@selector(onFlipDone:finished:context:)];
		[UIView setAnimationTransition:((card.isFace) ?
										UIViewAnimationTransitionFlipFromLeft : UIViewAnimationTransitionFlipFromRight)
							   forView:view cache:YES];
		[card removeFromSuperview];
		[view addSubview:card.backCard];
		[UIView commitAnimations];
		
		fc.isFaced = !card.isFace;
		
		//[card release];
		//[view release];
	}
}

- (void)onFlipDone:(NSString*)animationID finished:(NSNumber*)finished context:(void*)context {
	NSLog(@"onFlipDone %@ %@ %@", animationID, finished, context);
	FlashCard *fc = [cardA objectAtIndex: curCardFlip];
	if (!fc.isFaced && fc.hasSound) {
		NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:[[NSBundle mainBundle]
																		pathForResource:fc.file
																		ofType:@"mp3"
																		inDirectory:@"/"], [[NSBundle mainBundle] resourcePath]]];
		NSError *error;
		if (audioPlayer) {
			NSLog(@"clear previous audioplayer");
			[audioPlayer release];
		}
		audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
		if (audioPlayer == nil) {
			NSLog([error description]);				
		} else {
			[audioPlayer play];
		}		
	}
	curCardFlip = -1;
}

- (void)dealloc {
	[cardA release];
	_scrollView.delegate = nil;
	[_scrollView release];	
    [super dealloc];
}


@end
